package com.am.server.api.system.parameter.dao.rdb.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.am.server.api.system.parameter.dao.rdb.ParameterDao;
import com.am.server.api.system.parameter.model.dto.ParameterListQueryDto;
import com.am.server.api.system.parameter.model.entity.ParameterEntity;
import com.am.server.api.system.parameter.model.entity.QParameterEntity;
import com.am.server.api.system.parameter.repository.ParameterRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author 阮雪峰
 */
@Service
public class ParameterDaoImpl implements ParameterDao {
    private final JPAQueryFactory jpaQueryFactory;
    private final ParameterRepository parameterRepository;

    public ParameterDaoImpl(JPAQueryFactory jpaQueryFactory, final ParameterRepository parameterRepository) {
        this.jpaQueryFactory = jpaQueryFactory;
        this.parameterRepository = parameterRepository;
    }

    @Override
    public List<ParameterEntity> findAll() {
        return parameterRepository.findAll();
    }

    @Override
    public List<ParameterEntity> findAll(ParameterListQueryDto query) {
        QParameterEntity qParameterEntity = QParameterEntity.parameterEntity;

        Optional<ParameterListQueryDto> optional = Optional.of(query);
        BooleanBuilder booleanBuilder = new BooleanBuilder(qParameterEntity.id.isNotNull());
        optional.map(ParameterListQueryDto::getFullPath).filter(CharSequenceUtil::isNotBlank).ifPresent(obj -> booleanBuilder.and(qParameterEntity.fullPath.contains(obj)));
        optional.map(ParameterListQueryDto::getUniqueKey).filter(CharSequenceUtil::isNotBlank).ifPresent(obj -> booleanBuilder.and(qParameterEntity.uniqueKey.contains(obj)));
        optional.map(ParameterListQueryDto::getType).ifPresent(obj -> booleanBuilder.and(qParameterEntity.type.eq(obj)));

        return jpaQueryFactory.selectFrom(qParameterEntity).where(booleanBuilder.getValue()).fetch();
    }

    @Override
    public void saveAll(Collection<ParameterEntity> collection) {
        parameterRepository.saveAll(collection);
    }

    @Override
    public Optional<ParameterEntity> findByUniqueKey(String uniqueKey) {
        return parameterRepository.findByUniqueKey(uniqueKey);
    }

    @Override
    public void save(ParameterEntity parameter) {
        parameterRepository.save(parameter);
    }

    @Override
    public List<ParameterEntity> findByUniqueKeys(List<String> uniqueKeys) {
        return parameterRepository.findAllByUniqueKeyIn(uniqueKeys);
    }
}
